import {defineStore} from "pinia";
import {store} from "@/store";
import dictTypeApi from "@/api/system/type";
import storage from "@/utils/storage";

export const useDictStore = defineStore({
    id: "jcx-type-store",
    state: () => ({
        dictTypeList: storage.data.get("APP_DICT_LIST") || []
    }),
    actions: {
        setDictType(dictType) {
            if (dictType != null) {
                this.dictTypeList.push(dictType);
            }
        },
        setDictTypeList(dictTypeList) {
            this.dictTypeList = dictTypeList;
            storage.data.set("APP_DICT_LIST", this.dictTypeList);
        },
        clearDictTypeList() {
            this.dictTypeList = [];
            storage.data.remove("APP_DICT_LIST");
        },
        initDictTypeList() {
            this.clearDictTypeList();
            dictTypeApi.lists.get({enabled: true, isExtend: true}).then(response => {
                if (response.status) {
                    this.setDictTypeList(response.data.list);
                }
            })
        },
        getDictTypeList() {
            return this.dictTypeList;
        },
        getDictTypeByCode(code) {
            if (code == null && code === "") {
                return null;
            }
            try {
                for (let i = 0; i < this.dictTypeList.length; i++) {
                    if (this.dictTypeList[i].code === code) {
                        return this.dictTypeList[i];
                    }
                }
            } catch (e) {
                return null;
            }
        },
    }
});

export function useDictStoreHook() {
    return useDictStore(store);
}
